package com.zhenyi.api.gen;

import java.util.ArrayList;

import com.jfinal.kit.StrKit;
import com.utils.PathUtils;

import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class GenFormUtils {

	public static final int TYPE_TEXT = 1;
	public static final int TYPE_SELECTION = 2;
	public static final int TYPE_DATE_RANGE = 3;
	public static final int TYPE_DATE = 4;
	public static final int TYPE_TIME = 5;
	public static final int TYPE_CHECK_BOX = 6;
	public static final int TYPE_IMAGE = 7;
	public static final int TYPE_IMAGES = 8;
	public static final int TYPE_FILES = 9;
	public static final int TYPE_BUTTON = 10;

	private static final int INPUT_TYPE_TEXT = 1;
	private static final int INPUT_TYPE_NUMBER = 2;
	private static final int INPUT_TYPE_PASSWORD = 3;
	private static final int INPUT_TYPE_TEXT_AREA = 4;

	private ArrayList<String> dateRangeItems = new ArrayList<>();
	private StringBuffer dateRangeJsBuff = new StringBuffer();
	private StringBuffer imageJsBuff = new StringBuffer();
	private StringBuffer buttonJsBuff = new StringBuffer();

	/**
	 * 基本设置
	 * 
	 * @param template
	 * @param inputItem
	 * @return
	 */
	protected String setupBaseInfo(String template, JSONObject inputItem) {

		String label = inputItem.getStr("label", "");
		String vModel = inputItem.getStr("v-model", "");
		String placeholder = inputItem.getStr("placeholder", "");
		String span = inputItem.getStr("span", "12");
		// String swicherName = inputItem.getStr("swicherName");
		int isDisabled = inputItem.getInt("isDisabled", 0);
		int isClearable = inputItem.getInt("isClearable", 1);

		template = template.replace("TEMP_LABEL", label);

		template = template.replace("TEMP_V_MODEL", vModel);
		template = template.replace("TEMP_SPAN", span);
		if (isDisabled == 1) {
			template = template.replace("TEMP_IS_DISABLED", "disabled");
		} else {
			template = template.replace("TEMP_IS_DISABLED", "");
		}

		if (isClearable == 1) {
			template = template.replace("TEMP_CLEARABLE", "clearable");
		} else {
			template = template.replace("TEMP_CLEARABLE", "");
		}
		template = template.replace("TEMP_PLACEHOLDER", placeholder);

		return template;
	}

	protected String getButtonInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_button.html");
		template = setupBaseInfo(template, inputItem);

		String action = inputItem.getStr("action");
		template = template.replace("TEMP_ACTION", action);

		String js = getProjecTemplate("input_button.js");
		js = js.replace("TEMP_ACTION", action);
		buttonJsBuff.append(js);

		return template;
	}

	protected String getFilesInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_files.html");
		template = setupBaseInfo(template, inputItem);
		return template;
	}

	protected String getImagesInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_images.html");
		template = setupBaseInfo(template, inputItem);

		return template;
	}

	protected String getImageInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_image.html");
		template = setupBaseInfo(template, inputItem);

		String name = inputItem.getStr("name");
		String vModel = inputItem.getStr("v-model", "");

		String handlerName = name + "HandleAvatarSuccess";
		template = template.replace("TEMP_HANDLER", handlerName);

		String js = getProjecTemplate("input_image.js");
		js = js.replace("TEMP_HANDLER", handlerName);
		js = js.replace("TEMP_V_MODEL", vModel);
		imageJsBuff.append(js);

		return template;
	}

	protected String getTimeInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_time.html");
		template = setupBaseInfo(template, inputItem);

		String startTime = inputItem.getStr("startTime");
		String endTime = inputItem.getStr("endTime");
		String step = inputItem.getStr("step");

		template = template.replace("TEMP_START_TIME", startTime);
		template = template.replace("TEMP_END_TIME", endTime);
		template = template.replace("TEMP_STEP", step);

		return template;
	}

	protected String getDateInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_date.html");
		template = setupBaseInfo(template, inputItem);

		String format = inputItem.getStr("format");
		template = template.replace("TEMP_FORMAT", format);

		return template;
	}

	/**
	 * 单选框
	 * 
	 * @param inputItem
	 * @return
	 */
	protected String getCheckboxInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_checkbox.html");
		template = setupBaseInfo(template, inputItem);
		return template;
	}

	/**
	 * 日期范围
	 * 
	 * @param inputItem
	 * @return
	 */
	protected String getDateRangeInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_date_range.html");
		template = setupBaseInfo(template, inputItem);

		String format = inputItem.getStr("format");
		String name = inputItem.getStr("name");

		String rangeSeparator = inputItem.getStr("range-separator");
		String startPlaceholder = inputItem.getStr("start-placeholder");
		String endPlaceholder = inputItem.getStr("end-placeholder");

		JSONArray vModels = inputItem.getJSONArray("v-models");
		String model1 = String.valueOf(vModels.get(0));
		String model2 = String.valueOf(vModels.get(1));

		String js = getProjecTemplate("input_date_range.js");
		js = js.replace("TEMP_MODEL1", model1);
		js = js.replace("TEMP_MODEL2", model2);
		js = js.replace("TEMP_MODEL", name);

		dateRangeJsBuff.append(js);

		template = template.replace("TEMP_FORMAT", format);

		template = template.replace("TEMP_START_PLACEHOLDER", startPlaceholder);
		template = template.replace("TEMP_END_PLACEHOLDER", endPlaceholder);
		template = template.replace("TEMP_RANGE_SEPAEATOR", rangeSeparator);

		template = template.replace("TEMP_DATA", "dateRange." + name);

		dateRangeItems.add(name);

		return template;
	}

	/**
	 * 设置 单选框
	 * 
	 * @param inputItem
	 * @return
	 */
	protected String getSelectionInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_selection.html");
		template = setupBaseInfo(template, inputItem);

		String name = inputItem.getStr("name");
		JSONObject selection = inputItem.getJSONObject("selection");
		JSONArray selections = selection.getJSONArray("selections");
		JSONObject attributes = selection.getJSONObject("attributes");
		if (attributes != null) {
			String attrName = attributes.getStr("name");
			String label = attributes.getStr("label");
			String value = attributes.getStr("value");
			String temp = "<el-option v-for='item in {}' :key='item.{}' :label='item.{}' :value='item.{}'></el-option>";
			temp = StrFormatter.format(temp, attrName, value, label, value);
			template = template.replace("TEMP_OPTION", temp);
		} else if (selections != null) {
			StringBuffer optionBuff = new StringBuffer();
			for (Object object : selections) {
				JSONObject selectionItem = new JSONObject(object);
				String value = selectionItem.getStr("value");
				String label = selectionItem.getStr("label");
				String temp = "<el-option :key='" + value + "' label='" + label + "' :value='" + value
						+ "'></el-option>";
				optionBuff.append(temp);
			}
			template = template.replace("TEMP_OPTION", optionBuff.toString());
		}

		return template;
	}

	protected String getTextInput(JSONObject inputItem) {
		String template = getProjecTemplate("input_text.html");
		template = setupBaseInfo(template, inputItem);

		JSONObject text = inputItem.getJSONObject("text");
		int inputType = text.getInt("inputType", 1);

		if (inputType == INPUT_TYPE_TEXT) {
			template = template.replace("TEMP_TYPE", "text");
			template = template.replace("TEMP_ROWS", "");
		} else if (inputType == INPUT_TYPE_NUMBER) {
			template = template.replace("TEMP_TYPE", "number");
			template = template.replace("TEMP_ROWS", "");
		} else if (inputType == INPUT_TYPE_PASSWORD) {
			template = template.replace("TEMP_TYPE", "password");
			template = template.replace("TEMP_ROWS", "");
		} else if (inputType == INPUT_TYPE_TEXT_AREA) {
			template = template.replace("TEMP_TYPE", "textarea");
			int rows = text.getInt("rows", 5);
			template = template.replace("TEMP_ROWS", "rows='" + rows + "'");
		} else {
			template = template.replace("TEMP_TYPE", "text");
			template = template.replace("TEMP_ROWS", "");
		}

		return template;
	}

	protected String getProjecTemplate(String name) {
		String path = PathUtils.getFile("data", "template", name);
		FileReader fileReader = new FileReader(path);
		String value = fileReader.readString();
		return value;
	}

	protected String getFormTemplate() {
		return getProjecTemplate("form_temp.html");
	}

	public void run() {

		String formTemplate = getProjecTemplate("form_temp.html");

		String jsonPath = PathUtils.getFile("data", "gen.json");
		FileReader fileReader = new FileReader(jsonPath);
		String json = fileReader.readString();
		// System.out.println(json);
		JSONObject jsonObject = JSONUtil.parseObj(json);
		JSONArray input = jsonObject.getJSONArray("input");
		StringBuffer inputsHtml = new StringBuffer();
		for (Object object : input) {
			JSONObject inputItem = JSONUtil.parseObj(object);
			int type = inputItem.getInt("type");
			if (type == TYPE_TEXT) {
				String html = getTextInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_SELECTION) {
				String html = getSelectionInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_CHECK_BOX) {
				String html = getCheckboxInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_DATE_RANGE) {
				String html = getDateRangeInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_DATE) {
				String html = getDateInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_TIME) {
				String html = getTimeInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_IMAGE) {
				String html = getImageInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_IMAGES) {
				String html = getImagesInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_FILES) {
				String html = getFilesInput(inputItem);
				inputsHtml.append(html);
			} else if (type == TYPE_BUTTON) {
				String html = getButtonInput(inputItem);
				inputsHtml.append(html);
			}
		}

		JSONObject config = jsonObject.getJSONObject("config");
		String gutter = config.getStr("gutter", "20");
		String pageTitle = config.getStr("pageTitle");
		String menuIndex = config.getStr("menuIndex");
		String labelWidth = config.getStr("labelWidth", "80px");

		formTemplate = formTemplate.replace("TEMP_INPUTS", inputsHtml.toString());
		formTemplate = formTemplate.replace("TEMP_GUTTER", gutter + "");
		formTemplate = formTemplate.replace("TEMP_MENU_INDEX", menuIndex);
		formTemplate = formTemplate.replace("TEMP_LABEL_WIDTH", labelWidth);
		formTemplate = formTemplate.replace("TEMP_PAGE_TITLE", pageTitle);

		StringBuffer scriptBuff = new StringBuffer();
		JSONArray scriptArray = config.getJSONArray("script");
		for (Object object : scriptArray) {
			String path = String.valueOf(object);
			String temp = "<script src='" + path + "'></script>";
			scriptBuff.append(temp);
		}
		formTemplate = formTemplate.replace("TEMP_SCRIPT", scriptBuff.toString());

		StringBuffer cssBuff = new StringBuffer();
		JSONArray cssArray = config.getJSONArray("css");
		for (Object object : cssArray) {
			String path = String.valueOf(object);
			String temp = "<link href='" + path + "' rel='stylesheet'>";
			cssBuff.append(temp);
		}
		formTemplate = formTemplate.replace("TEMP_CSS", cssBuff.toString());

		StringBuffer bottomIncludeBuff = new StringBuffer();
		JSONArray bottomIncludeArray = config.getJSONArray("bottomInclude");
		for (Object object : bottomIncludeArray) {
			String path = String.valueOf(object);
			String temp = "<#include '" + path + "' />";
			bottomIncludeBuff.append(temp);
		}
		formTemplate = formTemplate.replace("TEMP_BOTTOM_INCLUDE", bottomIncludeBuff.toString());

		// TEMP_ATTRIBUTES
		StringBuffer attrBuff = new StringBuffer();
		JSONArray attributes = jsonObject.getJSONArray("attributes");
		for (Object object : attributes) {
			JSONObject attrItem = new JSONObject(object);
			String name = attrItem.getStr("name");
			// String attr = attrItem.getStr("attr");
			int type = attrItem.getInt("type", 1);
			if (type == 1) {
				String temp = name + ": toJson2(`${" + name + "!{}}`),";
				attrBuff.append(temp);
			} else if (type == 2) {
				String temp = name + ": toJson2(`${" + name + "![]}`),";
				attrBuff.append(temp);
			}
		}
		String values = attrBuff.toString();
		System.out.println(values);
		if (StrKit.notBlank(values)) {
			formTemplate = formTemplate.replace("TEMP_ATTRIBUTES", attrBuff.toString());
		} else {
			formTemplate = formTemplate.replace("TEMP_ATTRIBUTES", "");
		}

		String imageHandlerJsStr = imageJsBuff.toString();
		if (StrKit.isBlank(imageHandlerJsStr)) {
			formTemplate = formTemplate.replace("TEMP_IMAGE_HANDLER", "");
		} else {
			formTemplate = formTemplate.replace("TEMP_IMAGE_HANDLER", imageHandlerJsStr);
		}

		String buttonHandlerJsStr = buttonJsBuff.toString();
		if (StrKit.isBlank(buttonHandlerJsStr)) {
			formTemplate = formTemplate.replace("TEMP_BUTTON_HANDLER", "");
		} else {
			formTemplate = formTemplate.replace("TEMP_BUTTON_HANDLER", buttonHandlerJsStr);
		}

		formTemplate = formTemplate.replace("TEMP_SELECTION_OPTIONS", "");

		// 时间段
		if (dateRangeItems.size() > 0) {
			String dateRangeStr = "dateRange:{";
			for (String name : dateRangeItems) {
				dateRangeStr = dateRangeStr + name + ":[],";
			}
			dateRangeStr = dateRangeStr + "},";
			formTemplate = formTemplate.replace("TEMP_DATE_RANGES_JS", dateRangeJsBuff.toString());
			formTemplate = formTemplate.replace("TEMP_DATE_RANGES", dateRangeStr);
		} else {
			formTemplate = formTemplate.replace("TEMP_DATE_RANGES_JS", "");
			formTemplate = formTemplate.replace("TEMP_DATE_RANGES", "");
		}
		String tp = PathUtils.getFile("data", "template", "gen1.html");
		System.out.println(tp);
		FileWriter fileWriter = new FileWriter(tp);
		fileWriter.write(formTemplate);
	}

	public static void main(String[] args) {
		GenFormUtils utils = new GenFormUtils();
		utils.run();
	}
}
